﻿package net.wangit.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;

import net.wangit.context.ActionContext;


/**
 * 验证码
 * @author watson
 *
 */
public class ValidateCode {
	private static final String KEY = "net.wangit.util.ValidateCode";
	private static final int WIDTH = 60;
	private static final int HEIGHT = 20;

	public ValidateCode() {
	}

	public static BufferedImage createImage(HttpServletRequest request) {
		BufferedImage image = new BufferedImage(ValidateCode.WIDTH,
				ValidateCode.HEIGHT, 1);
		Graphics g = image.getGraphics();
		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, ValidateCode.WIDTH, ValidateCode.HEIGHT);
		g.setFont(new Font("Times New Roman", 0, 18));
		g.setColor(getRandColor(160, 200));
		Random random = new Random();
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(ValidateCode.WIDTH);
			int y = random.nextInt(ValidateCode.HEIGHT);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		String code = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			code = (new StringBuilder(String.valueOf(code))).append(rand)
					.toString();
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 13 * i + 6, 16);
		}

		g.dispose();
		request.getSession().setAttribute(ValidateCode.KEY, code);
		return image;
	}

	public static boolean validate(ActionContext ac, String code) {
		if (Checker.isEmpty(code))
			return false;
		else
			return code.equals(ac.getSessionAttribute(ValidateCode.KEY));
	}

	private static Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
}
